<?php
/**
 * @Author 张超.
 * @Copyright http://www.zhangchao.name
 * @Email 416716328@qq.com
 * @DateTime 2018/5/8 16:06
 * @Desc
 */

namespace app\common\controller;

use app\run\model\AuthGroup;
use app\run\model\AuthGroupAccess;
use app\run\model\MenusRule;
use \Auth;
use think\Controller;
use think\facade\Config;

class Run extends Error
{
    protected $userInfo;

    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        //读取缓存文件、并赋值
        $this->assign(['dev' => read_cache("develop")]);
        //权限检测、当前项目的权限、可选择显示、可不显示、但提示没有权限
        $auth = new Auth\Auth($this->request);
        //定义不需要权限访问的地址
        $noAuth = Config::get("auth.NOT_ALLOW_AUTH");
        //获取当前请求的路径地址
        $strAuth = $this->request->controller() . "/" . $this->request->action();
        //检查是否登录
        if (!$this->check_login()) {
            if (!$this->request->isAjax()) {
                return $this->redirect(url("Login/index"));
            }
            exit;
        } else {
            //如果已经登录
            $this->userInfo = json_decode(substr(base64_decode(session(Config::get("auth.DEFAULT_LOGIN_SESSION"))), 0, -6), true);
            $this->assign("user", $this->userInfo);
        }
        //读取已安装的插件
        $modules = getDirList(ADDONS_PATH);
        $addonsList = [];
        foreach ($modules as $key => $val) {
            $moduleConfig = ADDONS_PATH . DS . $val . DS . "config" . DS . "app.php";
            $addonsConfig = include $moduleConfig;
            if (isset($addonsConfig['status']) && $addonsConfig['status'] && isset($addonsConfig['name']) && $addonsConfig['name']) {
                $addonsList[$key]['addon_url'] = addonsUrl($val);
                $addonsList[$key]['title'] = $addonsConfig['title'];
            }
        }
        $this->assign("addon_url", $addonsList);
        //缓存当前访问路径、
        session("thisurl", $strAuth);
        //获取当前缓存中的路径
        $this->assign("thisurl", session("thisurl"));
        //输出当前访问的路径
        $this->assign("befurl", $strAuth);
        //如果有不需要权限控制的地址、则进行判断处理、以下代码位置不能变动
        if (!empty($noAuth)) {
            if (in_array(strtolower($strAuth), $noAuth)) {
                return true;
            }
        }
        if (!$auth->check($strAuth, $this->userInfo['id'])) {
//            exit("<script src='/static/run/static/layui/layui.js'></script><script>layui.use(['layer','jquery'],function () {var layer = layui.layer,$ = layui.jquery;layer.msg('您缺少访问权限、3秒后自动关闭！',{icon:2},function() {layer.closeAll();var index = parent.layer.getFrameIndex(window.name);parent.layer.close(index);})})</script>");
            if ($this->request->isAjax()) {
                $this->ajaxRuturn(400, "您没有权限访问该操作！");
            }
        }
    }

    public function layAjax($code, $msg, $count, $data)
    {
        // 返回JSON数据格式到客户端 包含状态信息
        header('Content-Type:application/json; charset=utf-8');
        $array['code'] = $code;
        $array['msg'] = $msg;
        $array['count'] = $count;
        $array['data'] = $data;
        exit(json_encode($array));
    }

    /**
     * @author by 张超 <Email:416716328@qq.com web:http://www.zhangchao.name>
     * @name 定义ajax请求返回的数据类型
     * @version 1.0.0
     * @funName ajaxRuturn
     * @param $code 状态码 200成功 400失败
     * @param $msg 返回的提示消息
     * @param $data 需要返回的数据
     * @return  Obj
     */
    public function ajaxRuturn($code, $msg, $data = [])
    {
        header('Content-Type:application/json; charset=utf-8');
        $array['status'] = $code;
        $array['msg'] = $msg;
        $array['data'] = $data;
        exit(json_encode($array));
    }

    /**
     * @author by 张超 <Email:416716328@qq.com web:http://www.zhangchao.name>
     * @name 获取当前用户所属的所有菜单
     * @version 1.0.0
     * @funName get_menus
     * @param $uid
     * @return  Obj
     */
    public function get_menus()
    {
        //判断是否开启了无权限、但显示的配置
        if (Config::set("auth.IS_SHOW_AUTH")) {
            $map[] = ['ismenu', 'eq', 1];
        } else {
            //查询用户所属的用户组
            $AuthGroupAccess = new AuthGroupAccess();
            $groupResult = $AuthGroupAccess->where('uid', $this->userInfo['id'])->find();
            if (!$groupResult) $this->ajaxRuturn(400, "参数错误！");
            $AuthGroup = new AuthGroup();
            $authGroupResult = $AuthGroup->where("id", $groupResult['group_id'])->find();
            if (!$authGroupResult) $this->ajaxRuturn(400, "参数错误！");
            //拆分权限
            $rules = explode(",", $authGroupResult['rules']);
            //组装条件
            $map[] = ['id', 'in', $rules];
            $map[] = ['ismenu', 'eq', 1];
        }
        $rulesModel = new MenusRule();
        $resultRules = $rulesModel->where($map)->select()->toArray();
        if (!$resultRules) $this->ajaxRuturn(400, "暂无相关菜单！");
        return $resultRules;
    }

    public function check_login()
    {
        if (session(Config::get("auth.DEFAULT_LOGIN_SESSION"))) {
            return true;
        }
        if ($this->request->controller() == 'Login') {
            return true;
        }
        return false;
    }
}